﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ideas2Realize.CommonInterfaces;
using StructureMap;
using StructureMap.Attributes;
using Ideas2Realize.Data.Business.Interface;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;

namespace Ideas2Realize.Controllers
{
    public abstract class BaseController : Controller
    {
        [SetterProperty]
        public IAuthorizationService AuthorizationService {get; set;}

        [SetterProperty]
        public IUserRepository UserRepository { get; set; }

        [SetterProperty]
        public IDeviationRepository DeviationRepository { get; set; }

        [SetterProperty]
        public INewsItemRepository NewsItemRepository { get; set; }

        public UserContext UserContext() {

            var user = UserRepository.GetByUsername(User.Identity.Name);
            return new UserContext(user);    
        }

        public BaseController()
        {
        }
        public void SetConfigs()
        {
            if (User != null)
            {
                if (User.Identity.IsAuthenticated)
                {
                    var user = UserRepository.GetByUsername(User.Identity.Name);

                    ViewBag.UserFullname = string.Format("{0} {1}",user.Firstname, user.Lastname);
                }
            }
        }

        protected JsonResult Error(Exception ex)
        {
            return Error(ex, false);
        }

        protected JsonResult Error(Exception ex, bool htmlContentType)
        {
            var error = new { success = false, data = new { errorMessage = ex.Message } };

            JsonResult result = new JsonResult();
            result.Data = error;

            if (htmlContentType)
                result.ContentType = "text/html";

            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            return result;
        }

        protected JsonResult Success(object data)
        {
            return Success(data, false);
        }

        protected JsonResult Success(object data, bool htmlContentType)
        {
            var success = new { success = true, data = data };

            JsonResult result = new JsonResult();
            result.Data = success;

             if(htmlContentType)
                result.ContentType = "text/html";

            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            return result;
        }

        protected XmlResult PagedResult<T>(PetaPoco.Page<T> pagedObject)
        {
            return new XmlResult(pagedObject);
        }

        protected ActionResult PagedViewResult<T>(PetaPoco.Page<T> pagedObject)
        {
            return View(pagedObject); 
        }
    }
}
